<template>
  <div class="dashboard-container">
    <div style="display:flex;flex-direction:row">
      <el-form ref="ruleForm" style="width:80%" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="姓名" prop="nickName">
              <el-input v-model="ruleForm.nickName" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="学号" prop="userName">
              <el-input v-model="ruleForm.userName" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="身份证" prop="idCard">
              <el-input v-model="ruleForm.idCard" />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="出生日期" prop="dateOfBirth">
              <el-date-picker
                v-model="ruleForm.dateOfBirth"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="手机号" prop="telephone">
              <el-input v-model="ruleForm.telephone" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="班级" prop="classRoomTotalName">
              <el-input v-model="ruleForm.classRoomTotalName" disabled />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="学制(年)" prop="academicYear">
              <el-input v-model="ruleForm.academicYear" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="学历" prop="culturalLevelId">
              <el-select v-model="ruleForm.culturalLevelId" disabled placeholder="请选择">
                <el-option
                  v-for="item in culturalLevelList"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="入学时间" prop="admissionYear">
              <el-input v-model="ruleForm.admissionYear" disabled />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="民族" prop="nationalityId">
              <el-select v-model="ruleForm.nationalityId" placeholder="请选择">
                <el-option
                  v-for="item in nationalityList"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="7">
            <el-form-item label="政治面貌" prop="politicalStatusId">
              <el-select v-model="ruleForm.politicalStatusId" placeholder="请选择">
                <el-option
                  v-for="item in politicalStatusList"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="7">
            <el-form-item label="是否付费" prop="isPay">
              <div style="display:flex;align-items:center">
                <span :style="'未缴费'==='未缴费'?`color:red`:`color:blue`">未缴费</span>
                <div style="margin-left:10px">
                  <el-link v-if="'未缴费'==='未缴费'" type="primary" @click="payForZFB">前往缴费</el-link>
                  <i v-if="'已缴费'==='未缴费'" class="el-icon-check" />
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="ruleForm.sex" disabled placeholder="请选择">
                <el-option
                  v-for="item in sexList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleForm.email" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="生源地" prop="area">
          <el-select v-model="provinceValue" filterable placeholder="请选择省份" @change="provinceChange">
            <el-option
              v-for="item in provinceList"
              :key="item.code"
              :label="item.value"
              :value="item.code"
            />
          </el-select>
          <el-select v-model="municipalValue" filterable placeholder="请选择市" @change="municipalChange">
            <el-option
              v-for="item in municipalList"
              :key="item.code"
              :label="item.value"
              :value="item.code"
            />
          </el-select>
          <el-select v-model="countyValue" filterable placeholder="请选择区" @change="countyChange">
            <el-option
              v-for="item in countyList"
              :key="item.code"
              :label="item.value"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="现居地址" prop="homeAddress">
          <el-input v-model="ruleForm.homeAddress" type="textarea" :rows="4" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">保存信息</el-button>
        </el-form-item>
      </el-form>
      <el-form inline class="demo-ruleForm">
        <el-form-item label="照片">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
          >
            <div
              slot="tip"
              style="color: red"
            >
              提示:仅允许上传"jpg"<br>文件大小不能超过500k!
            </div>
            <img v-if="imageResource" :src="imageResource" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { payZFB } from '@/api/pay'
import { getUserInfo, updateUserInfo } from '@/api/user'
import { getCodeList } from '@/api/code'
import { rules } from './const.js'
import { getToken } from '@/utils/auth'
import { getPhoto } from '@/api/file'

export default {
  name: 'Register',
  data() {
    rules
    return {
      imageResource: '',
      culturalLevelList: [],
      nationalityList: [],
      politicalStatusList: [],
      // 省市区
      provinceList: [],
      municipalList: [],
      countyList: [],
      provinceValue: null,
      municipalValue: null,
      countyValue: null,
      sexList: [],
      ruleForm: {
        nickName: '曾小龙',
        userName: '1900130302',
        idCard: '',
        dateOfBirth: '',
        telephone: '15343286965'
      },
      rules: {
      }
    }
  },
  computed: {
    uploadUrl() {
      return `${process.env.VUE_APP_BASE_API}/file/uploadImage?jwt=${getToken()}`
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    // 初始化数据
    init() {
      this.rules = rules
      // 这里的getCodeList和getUserInfo有渲染问题，按理说应该用promise.all
      getCodeList().then((res) => {
        const { culturalLevelList, nationalityList, politicalStatusList, areaList } = res
        this.culturalLevelList = culturalLevelList
        this.nationalityList = nationalityList
        this.politicalStatusList = politicalStatusList
        this.provinceList = areaList
        getUserInfo().then((res) => {
          this.ruleForm = res
          if (res.area?.length > 0) {
            this.areaInit(res.area.split(',').map(item => Number(item)))
          }
        })
      })
      getPhoto().then((res) => {
        if (res) {
          this.imageResource = `data:image/jpeg;base64,${res}`
        }
      })
    },
    // 支付宝支付
    payForZFB() {
      const data = { outTradeNo: '1', totalAmount: '6600', subject: '学费', body: '学费' }
      payZFB(data).then((res) => {
        document.querySelector('body').innerHTML = res// 查找到当前页面的body，将后台返回的form替换掉他的内容
        document.forms[0].submit() // 执行submit表单提交，让页面重定向，跳转到支付宝页面
      })
    },

    // 省份修改
    provinceChange(value) {
      this.ruleForm.area = null
      this.provinceValue = value
      const findMunicipal = this.provinceList.find(item => item.code === value)
      if (findMunicipal) {
        this.municipalValue = null
        this.countyValue = null
        this.municipalList = findMunicipal.children
      }
    },
    // 市修改
    municipalChange(value) {
      this.ruleForm.area = null
      this.municipalValue = value
      const findCounty = this.municipalList.find(item => item.code === value)
      if (findCounty) {
        this.countyValue = null
        this.countyList = findCounty.children
      }
    },
    // 区修改
    countyChange(value) {
      this.countyValue = value
      const { provinceValue, municipalValue, countyValue } = this
      this.ruleForm.area = `${provinceValue},${municipalValue},${countyValue}`
      console.log(this.ruleForm.area)
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('请检查所填信息是否属实，若已检查，点击确认?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            updateUserInfo(this.ruleForm).then(() => {
              this.$message({
                type: 'success',
                message: '保存成功!两秒后刷新页面'
              })
              setTimeout(() => {
                this.$router.go(0)
              }, 1000)
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消保存'
            })
          })
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 区域初始化
    areaInit(area) {
      this.provinceValue = area[0]
      const findMunicipal = this.provinceList.find(item => item.code === area[0])
      if (findMunicipal) {
        this.municipalList = findMunicipal.children
        this.municipalValue = area[1]
        const findCounty = this.municipalList.find(item => item.code === area[1])
        if (findCounty) {
          this.countyList = findCounty.children
          this.countyValue = area[2]
        }
      }
      this.ruleForm.birthplace = area
    },
    beforeAvatarUpload(file) {
      console.log('file', file)
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 < 500

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 500k!')
      }
      return isJPG && isLt2M
    },
    handleExceed() {
      // 图片超出上限
      this.$message.error('当前限制选择 1 个文件')
    },
    handleSuccess() {
      this.$message({
        type: 'success',
        message: '上传成功!'
      })
      this.$router.go(0)
    }

  }
}
</script>

<style lang="scss" scoped>

.dashboard {
  &-container {
    margin: 30px;
  }
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>
